//
// Created by gj on 16-2-21.
//

#include "PointerCounter.h"
#include <unistd.h>

int PointerCounter::decCount() {
    if (count == NULL) {
        LOG_W("PointerCounter decCount count is NULL");
        return 1;
    }
    int _count = (*count)--;
    if (_count == 1) {
        delete count;
        count = NULL;
    }
    return _count;
}


int PointerCounter::copy(PointerCounter &counter) {
    LOG_I("PointerCounter copy start: count = %p, %d.", count, getCount())
    counter.incCount();
    int32_t _count = decCount();
    count = counter.count;
    LOG_I("PointerCounter copy end: count = %p, %d.", count, getCount())
    return _count;
}

#ifdef FLAG_UNIT_TESTING

void pointer_counter_unit_testing() {
    LOG_CREATE_FUNC_DEBUG("test");
    LOG_I_FILE_FUNC("--> test start!")
    LOG_I(LOG_SEPARATOR)
    PointerCounter pointerCounter;
    for (int i = 0; i < 5; ++i) {
        LOG_I_FILE_FUNC("--> test 1 ->")
        PointerCounter a(pointerCounter);
        a = pointerCounter;
        pointerCounter = a;
        a.decCount();
        LOG_I_FILE_FUNC("--> test 1 <-")
    }
    sleep(1);
    LOG_I_FILE_FUNC("--> test 1 end...")
    LOG_I(LOG_SEPARATOR)
    PointerCounter c = pointerCounter;
    PointerCounter b;
    pointerCounter = b;
    for (int i = 0; i < 5; ++i) {
        LOG_I_FILE_FUNC("--> test 2 ->")
        PointerCounter a;
        pointerCounter = a;
        a = pointerCounter;
        a.decCount();
        LOG_I_FILE_FUNC("--> test 2 <-")
    }
    sleep(1);
    LOG_I_FILE_FUNC("--> test 2 end...")
    LOG_I(LOG_SEPARATOR)
    for (int i = 0; i < 5; ++i) {
        LOG_I_FILE_FUNC("--> test 3 ->")
        PointerCounter a(pointerCounter);
        c = b;
        c = a;
        pointerCounter = c;
        a = b;
        b = pointerCounter;
        a.decCount();
        LOG_I_FILE_FUNC("--> test 3 <-")
    }
    sleep(1);
    LOG_I_FILE_FUNC("--> test 3 end...")
    pointerCounter.decCount();
    c.decCount();
    b.decCount();
    sleep(1);
    LOG_I(LOG_SEPARATOR)
}

#endif